package com.polaris.live.ui.vip.fragment

import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.StringUtils
import com.polaris.live.adapter.vip.VipIdentityAdapter
import com.polaris.live.adapter.vip.VipPrivilegesAdapter
import com.polaris.live.common.constant.BizEventConst
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.event.EventMessage
import com.polaris.live.common.ext.autoDp
import com.polaris.live.common.ext.setOnScrollChangeListenerCompat
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.base2.BaseVbFragment
import com.polaris.live.common.network.parseState
import com.polaris.live.common.util.AppCodeUtils
import com.polaris.live.common.util.NavigationBarUtils
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.databinding.FragmentVipCenterLevelBinding
import com.polaris.live.dialog.VipBuyDialog
import com.polaris.live.dialog.VipBuyGiveDialog
import com.polaris.live.dialog.VipBuySuccessfulDialog
import com.polaris.live.dialog.VipGiveSuccessfulDialog
import com.polaris.live.dialog_fragment.GiveFragmentDialog
import com.polaris.live.popup.GlobalPopupManager
import com.polaris.live.popup.VipPrivilegePopup
import com.polaris.live.resp.back_resp.UserVipIdentity
import com.polaris.live.resp.back_resp.UserVipLevel
import com.polaris.live.resp.back_resp.UserVipPrivilege
import com.polaris.live.translation.R
import com.polaris.live.translation.R.string.buy
import com.polaris.live.translation.R.string.renew
import com.polaris.live.utils.VipStyle
import com.polaris.live.utils.VipStyleBean
import com.polaris.live.utils.file.FileUtils
import com.polaris.live.utils.playAsync2
import com.polaris.live.viewmodel.VipCenterLevelViewModel
import org.greenrobot.eventbus.EventBus
import java.io.File

/**
 * VipCenterLevelFragment
 *
 * @author Created by 天晴 on 2024/12/10 10:40
 * @since 1.0.0
 **/
class VipCenterLevelFragment : BaseVbFragment<VipCenterLevelViewModel, FragmentVipCenterLevelBinding>() {

    val mLevel: Long by lazy { arguments?.getLong("level") ?: 0L }

    private var mUserVipLevels: UserVipLevel? = null

    private val mIdentityAdapter by lazy { VipIdentityAdapter(mLevel) }

    private val mVipPrivilegesAdapter by lazy { VipPrivilegesAdapter(mLevel) }

    private val mVipStyleBean: VipStyleBean by lazy {
        VipStyle.getVipStyle(mLevel)
    }

    private var mIdTitlePagInit = false
    private var mMedalTitlePagInit = false

    override fun initView(savedInstanceState: Bundle?) {
        mVipStyleBean.apply {
            mBinding.root.setBackgroundColor(ColorUtils.getColor(vipMainBgColor))
            mBinding.titleImg.setImageResource(vipTitle)
            mBinding.medalTitleImg.setImageResource(vipMedalTitle)
            mBinding.idTitleImg.setImageResource(vipIdentity)
            mBinding.privilegesLl.setBackgroundResource(vipMainPrivilegesColor)
            mBinding.bottomBuyLl.setBackgroundResource(vipBuyBottomBg)
            mBinding.buyBg.setBackgroundResource(vipBuyBg)
            mBinding.givePriceTv.setTextColor(ColorUtils.getColor(vipBuyColor))
            mBinding.giveDayTv.setTextColor(ColorUtils.getColor(vipBuyColor))
            mBinding.givePriceTv2.setTextColor(ColorUtils.getColor(vipOriginalColor))
            mBinding.giveDayTv2.setTextColor(ColorUtils.getColor(vipOriginalColor))
            mBinding.titleBgView.setBackgroundColor(ColorUtils.getColor(vipMainBgColor))
        }

        val bottomView = mBinding.bottom
        val lp = bottomView.layoutParams as ViewGroup.LayoutParams
        lp.height = NavigationBarUtils.getNavigationBarHeight(requireContext())
        bottomView.layoutParams = lp

        mBinding.identityRecycler.apply {
            layoutManager = GridLayoutManager(requireContext(), 3)
            adapter = mIdentityAdapter
            itemAnimator = null
        }

        mBinding.privilegesRecycler.apply {
            layoutManager = GridLayoutManager(requireContext(), 3)
            adapter = mVipPrivilegesAdapter
            itemAnimator = null
        }
        val reserveIdentityList = arrayListOf<UserVipIdentity>() //占位数据
        val reservePrivilegeList = arrayListOf<UserVipPrivilege>() //占位数据
        repeat(6) {
            reserveIdentityList.add(
                UserVipIdentity(
                    null,
                    null,
                    null,
                    "-1",
                    "",
                    null,
                    "",
                    "",
                    null,
                    null
                )
            )
            reservePrivilegeList.add(
                UserVipPrivilege(
                    false,
                    null,
                    "-1",
                    "",
                    "",
                    "",
                    null,
                    null
                )
            )
        }
        mIdentityAdapter.setList(reserveIdentityList)
        mVipPrivilegesAdapter.setList(reservePrivilegeList)

        initListener()
        initObserver()

        if (AppCodeUtils.isAR()) {
            mBinding.identityLeft.scaleX = -1f
            mBinding.privilegesLeft.scaleX = -1f
            mBinding.identityRight.scaleX = -1f
            mBinding.privilegesRight.scaleX = -1f
        }

        mUserVipLevels?.let {
            setData(it)
        }

    }

    fun setData(userVipLevels: UserVipLevel) {
        this.mUserVipLevels = userVipLevels
        withLoaded {
            val frameEffectPath = FileUtils.getFilePath(FileUtils.getPagFile(), userVipLevels.frameEffectUrl)
            if (!File(frameEffectPath).exists()) {
                mBinding.idTitleImg.visibility = View.VISIBLE
            }
            val displayEffectPath = FileUtils.getFilePath(FileUtils.getPagFile(), userVipLevels.displayEffectUrl)
            if (!File(displayEffectPath).exists()) {
                mBinding.medalTitleImg.visibility = View.VISIBLE
            }
            mBinding.idTitlePag.playAsync2(lifecycleScope, userVipLevels.frameEffectUrl, playCallBack = {
                mBinding.idTitleImg.visibility = View.GONE
                mIdTitlePagInit = true
            })
            mBinding.medalTitlePag.playAsync2(lifecycleScope, userVipLevels.displayEffectUrl, playCallBack = {
                mBinding.medalTitleImg.visibility = View.GONE
                mMedalTitlePagInit = true
            })

            mBinding.dayTv.text = "/${userVipLevels.priceDays}days"
            mBinding.giveDayTv.text = "/${userVipLevels.priceDays}days"

            mIdentityAdapter.setList(userVipLevels.identities)
            mVipPrivilegesAdapter.setList(userVipLevels.privileges)
            if (userVipLevels.bizType == 0L) { //没有开会员，且未在续费优惠期内
                mBinding.buyBtnTv.text = StringUtils.getString(buy)
                mBinding.priceTv.text = "${userVipLevels.price}"
                mBinding.givePriceTips.text = StringUtils.getString(R.string.renewal_price)
                mBinding.givePriceTv.text = "${userVipLevels.renewalPrice}"
                mBinding.lineGive.visibility = View.GONE
                mBinding.periodValidityTv.visibility = View.GONE
                mBinding.yuanCl.visibility = View.VISIBLE
                mBinding.yuanCl2.visibility = View.GONE
            } else {
                mBinding.buyBtnTv.text = StringUtils.getString(renew)
                mBinding.priceTv.text = "${userVipLevels.renewalPrice}"
                mBinding.givePriceTips.text = StringUtils.getString(R.string.original_price_colon)
                mBinding.givePriceTv.text = "${userVipLevels.price}"
                mBinding.lineGive.visibility = View.VISIBLE

                mBinding.givePriceTv2.text = "${userVipLevels.price}"
                mBinding.giveDayTv2.text = "/${userVipLevels.priceDays}days"
                mBinding.periodValidityTv.visibility = View.VISIBLE
                mBinding.yuanCl.visibility = View.GONE
                mBinding.yuanCl2.visibility = View.VISIBLE
            }
            mBinding.identityCountTv.text = "${userVipLevels.identities.size}"
            val count = userVipLevels.privileges.filter { it.active }.size
            mBinding.privilegesCountTv.text = "$count/${userVipLevels.privileges.size}"

            when (userVipLevels.bizType) {
                1L -> { //续费期内
                    mBinding.periodValidityTv.text = StringUtils.getString(
                        R.string.remaining_validity_period_days,
                        userVipLevels.renewalDays
                    )
                }
                2L -> {
                    val days = userVipLevels.days
                    mBinding.periodValidityTv.text = StringUtils.getString(
                        R.string.remaining_validity_period_days,
                        days
                    )
                }
                3L -> {
                    val days = userVipLevels.trialDays
                    mBinding.periodValidityTv.text = StringUtils.getString(
                        R.string.remaining_validity_period_days,
                        days
                    )
                }
                4L -> {
                    val day2 = userVipLevels.days + userVipLevels.trialDays
                    mBinding.periodValidityTv.text = StringUtils.getString(
                        R.string.remaining_validity_period_days,
                        day2
                    )
                }
            }

        }
    }

    private fun initListener() {
        mIdentityAdapter.setOnItemClickListener { adapter, view, position ->
            mUserVipLevels?.let {
                VipPrivilegePopup.show(requireContext(), false, position, it) {}
            }

        }
        mVipPrivilegesAdapter.setOnItemClickListener { adapter, view, position ->
            mUserVipLevels?.let {
                VipPrivilegePopup.show(requireContext(), false, (mIdentityAdapter.data.size + position), it) {}
            }
        }
        mBinding.buyBtnTv.setOnSingleClickListener {
            mUserVipLevels?.let {
                var price = if (it.days == 0L && it.trialDays == 0L && it.renewalDays == 0L) { //没有开会员，且未在续费优惠期内
                    it.price
                } else {
                    it.renewalPrice
                }
                VipBuyDialog.show(requireContext(), it.level, price, it.priceDays) {
                    mViewModel.vipBuy(it.level)
                }
            }

        }
        mBinding.giveBtnTv.setOnSingleClickListener {
            mUserVipLevels?.let { data ->
                GiveFragmentDialog.show(requireContext()) {
                    this.dismiss()
                    VipBuyGiveDialog.show(requireContext(), data.level, data.price, data.priceDays, it.nickname) {
                        mViewModel.vipBuy(data.level, it.userId)
                    }
                }
            }

        }
    }

    private fun initObserver() {
        mBinding.nesScrollView.setOnScrollChangeListenerCompat { scrollY ->
            val alpha = (scrollY / 120.autoDp.toFloat()).coerceIn(0f, 1f)
            mBinding.titleBgView.alpha = alpha

        }
        mViewModel.vipBuyLiveData.observe(this) { resultState ->
            parseState(resultState, { req ->
                EventBus.getDefault().post(EventMessage(BizEventConst.INFO_UPDATA))
                upData?.invoke()
                mUserVipLevels?.let { data ->
                    if (req.otherUserId == null) {
                        VipBuySuccessfulDialog.show(requireContext(), req.vipLevel, data.priceDays) {
                            toMineVip?.invoke(req.vipLevel.toInt())
                        }
                    } else {
                        VipGiveSuccessfulDialog.show(requireContext(), req.vipLevel, data.priceDays)
                    }
                }
            }, {
                ToastGravity.showGravity(it.errorMsg)
                if (it.errCode == CommonConst.ErrorCode.SENDGIFT) {
                    GlobalPopupManager.showRechargePopup(
                        requireContext(),
                        mViewModel,
                        isNeedBottom = true, onRechargeOk = {
                            EventBus.getDefault().post(EventMessage(BizEventConst.INFO_UPDATA))
                        })
                }
            })
        }
    }

    private var upData: (() -> Unit)? = null
    fun upData(back: () -> Unit) {
        this.upData = back
    }

    private var toMineVip: ((index: Int) -> Unit)? = null
    fun toVip(toMineVip: (index: Int) -> Unit) {
        this.toMineVip = toMineVip
    }

    override fun onResume() {
        super.onResume()
        if (mIdTitlePagInit) {
            mBinding.idTitlePag.setCurrentFrame(0)
            if (!mBinding.idTitlePag.isPlaying) {
                mBinding.idTitlePag.play()
            }
        }
        if (mMedalTitlePagInit) {
            mBinding.medalTitlePag.setCurrentFrame(0)
            if (!mBinding.medalTitlePag.isPlaying) {
                mBinding.medalTitlePag.play()
            }
        }
    }

    override fun onPause() {
        super.onPause()
        if (mIdTitlePagInit) {
            if (mBinding.idTitlePag.isPlaying) {
                mBinding.idTitlePag.pause()
                mBinding.idTitlePag.setCurrentFrame(0)
            }
        }
        if (mMedalTitlePagInit) {
            if (mBinding.medalTitlePag.isPlaying) {
                mBinding.medalTitlePag.pause()
                mBinding.medalTitlePag.setCurrentFrame(0)
            }
        }
    }

}